<template>
  <div class="cesium-draw">
    <div id="cesium-drawer"></div>
    <div class="mouse-postion">{{ nowPostion.wgs84 }}</div>
    <div class="tool-box">
      <!-- <div class="slider-box-wrapper"><slider-box v-model:value="terrainExaggeration" :max="2" /></div> -->
      <!-- <div class="slider-box-wrapper"><slider-box v-model:value="height" :max="100" :min="-100" :step="1" /></div> -->
      <!-- <div class="select-box-wrapper"><select-box :options="layerOptions" /></div> -->
      <!-- <div class="select-box-wrapper"><select-box :options="entityToolbarOptions" /></div>
          <div class="select-box-wrapper"><select-box :options="sizeOptions" /></div>
          <div class="select-box-wrapper"><a-checkbox v-model:checked="shadows">shadows</a-checkbox></div>
          <div class="select-box-wrapper"><a-checkbox v-model:checked="softShadows">soft shadows</a-checkbox></div>
          <div class="select-box-wrapper"><a-checkbox v-model:checked="terrainShadows">terrain shadows</a-checkbox></div> -->
      <!-- <div class="select-box-wrapper"><a-checkbox v-model:checked="picking">选择</a-checkbox></div> -->
      <div id="menu">
        <!-- <p><button @click="onClick('play')">播放</button></p> -->
        <!-- <p><button @click="onClick('stop')">暂停</button></p> -->
      </div>
    </div>
  </div>
</template>

<script>
import { DownOutlined, EditOutlined } from '@ant-design/icons-vue';
import { defineComponent, ref, watch } from 'vue';
import * as Cesium from '@cesium/Source/Cesium.js';
import MousePosition from '@functional/utils/mousePosition';
import sliderBox from '@components/widgets/slider-box';

export default defineComponent({
  name: 'satelliteRadar', // 卫星雷达
  components: { DownOutlined, EditOutlined, sliderBox },
  setup() {
    return {
      viewer: null,
      synchronizer: null,
      isRepeating: true,
      videoOverlay: true
    };
  },
  data() {
    return {
      nowPostion: {}
    };
  },
  computed: {},
  watch: {},
  mounted() {
    this.initViewer();
  },
  beforeUnmount() {
    if (this.viewer) {
      this.viewer.destroy();
      this.viewer = null;
    }
  },
  methods: {
    onViewerInited(viewer) {
      let vm = this;
      new MousePosition(viewer, pos => {
        vm.nowPostion = pos;
      });
    },

    initViewer() {
      let vm = this;
      Cesium.Ion.defaultAccessToken = $accessToken.default;
      let osm = new Cesium.ArcGisMapServerImageryProvider({
        // url: '//services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer'
        url: '//services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer'
      });
      var viewer = new Cesium.Viewer('cesium-drawer', {
        imageryProvider: osm,
        contextOptions: {
          webgl: {
            alpha: true
          }
        },
        shadows: true,
        animation: false,
        // baseLayerPicker: false,
        fullscreenButton: false,
        vrButton: false,
        homeButton: false,
        timeline: false,
        selectionIndicator: false,
        infoBox: false,
        // 注释时相当于使用默认地形，解开注释相当于使用全球地形
        // terrainProvider,
        shouldAnimate: true
      });

      //开启深度检测
      viewer.scene.globe.depthTestAgainstTerrain = true;

      this.viewer = viewer;
      this.onViewerInited(viewer);
      this.initEffects();

      // this.viewer.flyTo(this.viewer.entities);
    },
    initEffects() {
      let vm = this;
      const viewer = this.viewer;

      var scene = viewer.scene;
      // 1 雷达位置计算
      // 1.1 雷达的高度
      var length = 400000.0;
      // 1.2 地面位置(垂直地面)
      var positionOnEllipsoid = Cesium.Cartesian3.fromDegrees(112.39, 28.9);
      // 1.3 中心位置
      var centerOnEllipsoid = Cesium.Cartesian3.fromDegrees(112.39, 28.9, length * 0.5);
      // 1.4 顶部位置(卫星位置)
      var topOnEllipsoid = Cesium.Cartesian3.fromDegrees(112.39, 28.9, length);
      // 1.5 矩阵计算
      var modelMatrix = Cesium.Matrix4.multiplyByTranslation(
        Cesium.Transforms.eastNorthUpToFixedFrame(positionOnEllipsoid),
        new Cesium.Cartesian3(0.0, 0.0, length * 0.5),
        new Cesium.Matrix4()
      );
      // 2 相机飞入特定位置
      viewer.camera.flyToBoundingSphere(new Cesium.BoundingSphere(centerOnEllipsoid, length));
      // 3 创建卫星
      var imageUri =
        '';
      var billboards = scene.primitives.add(new Cesium.BillboardCollection());
      billboards.add({
        // image : './Tutorials/satellite1.svg',
        image: imageUri,
        position: topOnEllipsoid,
        horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        pixelOffset: new Cesium.Cartesian2(-10, 10),
        scale: 0.3
      });
      // 4 创建雷达放射波
      // 4.1 先创建Geometry
      var cylinderGeometry = new Cesium.CylinderGeometry({
        length: length,
        topRadius: 0.0,
        bottomRadius: length * 0.5,
        // vertexFormat : Cesium.PerInstanceColorAppearance.VERTEX_FORMAT
        vertexFormat: Cesium.MaterialAppearance.MaterialSupport.TEXTURED.vertexFormat
      });
      // 4.2 创建GeometryInstance
      var redCone = new Cesium.GeometryInstance({
        geometry: cylinderGeometry,
        modelMatrix: modelMatrix
        // attributes : {
        //     color : Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.RED)
        // }
      });
      // 4.3 创建Primitive
      var radar = scene.primitives.add(
        new Cesium.Primitive({
          geometryInstances: [redCone],
          // appearance : new Cesium.PerInstanceColorAppearance({
          //     closed : true,
          //     translucent: false
          // })
          appearance: new Cesium.MaterialAppearance({
            // 贴图像纹理
            // material: Cesium.Material.fromType('Image', {
            //     image: './images/earth.png'
            // }),
            // 贴棋盘纹理
            // material: Cesium.Material.fromType('Checkerboard'),
            // 自定义纹理
            material: new Cesium.Material({
              fabric: {
                type: 'VtxfShader1',
                uniforms: {
                  color: new Cesium.Color(0.2, 1.0, 0.0, 0.5),
                  repeat: 30.0,
                  offset: 0.0,
                  thickness: 0.3
                },
                source: `
                    uniform vec4 color;
                    uniform float repeat;
                    uniform float offset;
                    uniform float thickness;
                    czm_material czm_getMaterial(czm_materialInput materialInput){
                        czm_material material = czm_getDefaultMaterial(materialInput);
                        float sp = 1.0/repeat;
                        vec2 st = materialInput.st;
                        float dis = distance(st, vec2(0.5));
                        float m = mod(dis + offset, sp);
                        float a = step(sp*(1.0-thickness), m);
                        material.diffuse = color.rgb;
                        material.alpha = a * color.a;
                        return material;
                    }
                `
              },
              translucent: false
            }),
            faceForward: false, // 当绘制的三角面片法向不能朝向视点时，自动翻转法向，从而避免法向计算后发黑等问题
            closed: true // 是否为封闭体，实际上执行的是是否进行背面裁剪
          })
        })
      );
      // 5 动态修改雷达材质中的offset变量，从而实现动态效果。
      viewer.scene.preUpdate.addEventListener(function() {
        var offset = radar.appearance.material.uniforms.offset;
        offset -= 0.001;
        if (offset > 1.0) {
          offset = 0.0;
        }
        radar.appearance.material.uniforms.offset = offset;
      });
    }
  }
});
</script>

<style scoped lang="less">
.cesium-draw {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
  color: white;
  font-size: 14px;

  #cesium-drawer {
    width: 100%;
    height: 100%;
    overflow: hidden;
    :deep(.cesium-viewer-bottom) {
      display: none !important;
    }
  }

  .mouse-postion {
    position: absolute;
    bottom: 10px;
    right: 10px;
    font-size: 14px;
    padding: 8px 12px;
    line-height: 16px;
    color: white;
    z-index: 9999;
    background-color: rgba(40, 48, 60, 1);
    border-radius: 3px;
    opacity: 0.8;
  }
}

.tool-box {
  position: absolute;
  top: 70px;
  left: 10px;
  z-index: 9;

  #menu {
    padding-top: 20px;
    button {
      background-color: rgba(0, 0, 0, 0.75);
      border-color: rgba(0, 0, 0, 0);
      cursor: pointer;
      transition: all 500ms;
      &:hover {
        opacity: 0.75;
      }
    }
  }

  .slider-box-wrapper {
    width: 18em;
    padding: 0 10px;
    background-color: rgba(0, 0, 0, 0.75);
    margin-bottom: 10px;
  }

  .select-box-wrapper {
    padding: 5px 15px;
    background-color: rgba(0, 0, 0, 0.75);
    margin-bottom: 10px;
    width: auto;
  }
}
</style>
